<?php

use GuzzleHttp\Client;

class Mp
{
    private $code;

    /**
     * @throws Exception
     */
    public function __construct($code)
    {
        if (empty($code)) {
            throw new Exception('参数缺失');
        }
        $this->code = $code;
    }

    /**
     * @throws Exception
     */
    public function oauth()
    {
        $config = require_once __DIR__ . '/config.php';
        $result = (new Client())->get('https://api.weixin.qq.com/sns/oauth2/access_token',
            [
                'query' => [
                    'appid' => $config['mp_appid'],
                    'secret' => $config['mp_secret'],
                    'code' => $this->code,
                    'grant_type' => 'authorization_code'
                ]
            ]);
        $token = json_decode((string)$result->getBody(), true);
        if ($token['errcode'] > 0) {
            throw new Exception($token['errmsg'], $token['errcode']);
        }
        return $token;
    }

    /**
     * @throws Exception
     */
    protected function getMpUser($data)
    {
        $result = (new Client())->get('https://api.weixin.qq.com/sns/userinfo',
            [
                'query' => [
                    'access_token' => $data['access_token'],
                    'openid' => $data['openid'],
                    'lang' => 'zh_CN',
                    'scope' => 'snsapi_userinfo'
                ]
            ]);
        $userInfo = json_decode((string)$result->getBody(), true);
        if ($userInfo['errcode'] > 0) {
            throw new Exception($userInfo['errmsg'], $userInfo['errcode']);
        }
        return $userInfo;
    }
}